<!--
 * @Author: 宋绍华
 * @Date: 2024-11-11 17:16:16
 * @LastEditors: 宋绍华
 * @LastEditTime: 2024-12-23 16:59:57
 * @FilePath: \sr_system_manager_ui\src\views\project\manage\publishNotices.vue
 * @Description: 发布消息通知
-->
<template>
  <div class="publish-notices">
    <div class="title">
      发布申报通知
    </div>
    <div class="publish-notices-content">
      <el-form label-width="70px">
        <el-form-item label="通知名称">
          <el-input :maxlength="50" v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="项目分类">
          <el-select placeholder="请选择" v-model="form.projectType" style="width: 400px">
            <el-option v-for="item in dictList" :key="item.dataId" :label="item.dataName" :value="item.dataId" />
          </el-select>

          <el-button link type="primary" ml-10px @click="open = true">
            添加项目类目
          </el-button>
        </el-form-item>

        <el-form-item label="年度" style="width: 470px">
          <el-select placeholder="请选择" v-model="form.statisticsYear" style="width: 400px">
            <el-option v-for="item in yearsList" :key="item.dataId" :label="item.dataName" :value="item.dataId" />
          </el-select>
        </el-form-item>
        <el-form-item label="申报时间" style="width: 470px">
          <el-date-picker value-format="YYYY-MM-DD" v-model="times" :disabled-date="disabledDate" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="通知内容">
          <editor v-model="form.content" :style="{ width: '100%' }" :min-height="320" />
        </el-form-item>
        <el-form-item label="通知附件">
          <FileUpload drag :limit="15" :is-show-tip="false" @update:modelValue="update" :modelValue="fileList" :fileSize="10" />
        </el-form-item>
      </el-form>
    </div>

    <div class="publish-notices-btns">
      <el-button @click="publish(0)">保存</el-button>
      <el-button type="primary" @click="publish(1)">发布</el-button>
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog title="添加项目分类" v-model="open" width="500px" append-to-body>
      <el-form @submit.native.prevent>
        <el-form-item label="项目分类名称" prop="remark">
          <el-input :maxlength="50" v-model="typeName" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click.stop="submitForm">确 定</el-button>
          <el-button @click="closeModal">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getDicListApi, getProjectNoticesDetailsApi, projectCreateNoticesApi, projectUpdateNoticesApi } from '@/api/project';
import { BaseSuccessRespDTO, DictionaryListRespVO } from '@/api/project/types';
import { projectNatureEnum } from '@/utils/constEnum';
import { getDicListById } from '../utils';
import { dictionaryCreateApi } from '@/api/system/dict';
import formateDate from '@/utils/formateDate';
const times = ref([])

const open = ref(false);
const route = useRoute()
const dictList = ref<DictionaryListRespVO[]>([])
const yearsList = ref<DictionaryListRespVO[]>([])
const { proxy } = getCurrentInstance();
let typeBaseName = '';
const fileList = ref([])

const typeName = ref('');
const form = ref({
  content: '',
  declareEndTime: undefined,
  declareStartTime: undefined,
  fileIds: [],
  isDirectPublish: true,
  projectType: undefined,
  statisticsYear: undefined,
  title: '',
  projectNature: Number(route.query.projectNature || 1),
  id: undefined
})

const handleDictList = (res) => {
  const code = Number(route.query.projectNature) === projectNatureEnum.projectNatureSchool ? 27 : 5
  typeBaseName = res.filter(i => i.code === code)[0]?.name
  
  // TODO 判断是否有字典
  dictList.value = getDicListById(code, res)
}

// 获取相关字典
const { run: getDicList } = useRequest(getDicListApi, {
  manual: true,
  onSuccess: (res) => {
    handleDictList(res)
    yearsList.value = getDicListById(2, res)
  }
})

// const clearForm = () => {
//   form.value = {
//     content: '',
//     declareEndTime: undefined,
//     declareStartTime: undefined,
//     fileIds: [],
//     isDirectPublish: false,
//     projectType: undefined,
//     statisticsYear: undefined,
//     title: '',
//     id: undefined
//   }
// }

// 获取消息详情
const { run: getProjectNoticesDetails } = useRequest(getProjectNoticesDetailsApi, {
  manual: true,
  onSuccess: (response) => {
    Object.keys(form.value).forEach((key) => {
      form.value[key] = response[key]
    })
    
    form.value.declareEndTime = formateDate(response.declareEndTime).format('YYYY-MM-DD')
    form.value.declareStartTime = formateDate(response.declareStartTime).format('YYYY-MM-DD')
    times.value = [form.value.declareStartTime, form.value.declareEndTime]
    form.value.id = response.id
    console.log(response, 'response', form.value.declareEndTime);
    fileList.value = response.attachmentFileInfoDTOList || []
  }
})

// 发布消息
const { runAsync: createNotices } = useRequest(projectCreateNoticesApi, {
  manual: true,
  onSuccess: (response: BaseSuccessRespDTO, params) => {
    if (response.isSuccess) {
      ElMessage({
        message: params[0].isDirectPublish ? '创建成功' : '保存成功', 
        type: 'success',
      })
      form.value.id = response.id
      // 关闭当前标签
      proxy.$tab.closePage()
    }
  }
})
// 发布消息
const { runAsync: updateNotices } = useRequest(projectUpdateNoticesApi, {
  manual: true,
  onSuccess: (response: BaseSuccessRespDTO) => {
    console.log(response, 'response');

    if (response.isSuccess) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      
      // 关闭当前标签
      proxy.$tab.closePage()
    }
  }
})

// 创建字段
const { run: dicCreate } = useRequest(dictionaryCreateApi, {
  manual: true,
  onSuccess: (response: BaseSuccessRespDTO) => {

    if (response.isSuccess) {
      typeName.value = ''
      ElMessage({
        message: '创建成功',
        type: 'success',
      })
      open.value = false;
      getDicList({})
    }
  }
})


// 校验表单
const checkForm = () => {
  if (!(form.value.declareStartTime && form.value.declareEndTime)) {
    ElMessage.error('请选择开始时间和结束时间')
    return false
  }

  if (!form.value.content) {
    ElMessage.error('请填写通知内容')
    return false
  }

  if (!form.value.title) {
    ElMessage.error('请填写通知标题')
    return false
  }

  if (!form.value.projectType) {
    ElMessage.error('请选择项目分类')
    return false
  }

  if (!form.value.statisticsYear) {
    ElMessage.error('请选择统计年度')
    return false
  }

  return true
}

const publish = async (type: number) => {
  console.log('保存')
  form.value.declareStartTime = times.value[0]
  form.value.declareEndTime = times.value[1]
  const isPass = checkForm()
  if (!isPass) return
  
  if (form.value?.id) {
    await updateNotices({ ...form.value, isDirectPublish: type === 1 })
  } else {
    await createNotices({ ...form.value, isDirectPublish: type === 1 || !!form.value?.id || false })
  }
}

// 设置日期
const disabledDate = (time) => {
  const date = new Date(time)
  return date.getTime() < Date.now()
}

// 关闭弹窗
const closeModal = () => {
  typeName.value = '';
  open.value = false;
}

const submitForm = () => {
  console.log('提交')
  dicCreate({
    name: typeBaseName,
    dataName: typeName.value
  })
}

function update(val) {
  fileList.value = val
  form.value.fileIds = val.map(i => i.id)
}

onMounted(() => {
  // console.log(window.sessionStorage.getItem('projectNoticeForm'), '--');
  
  // if (window.sessionStorage.getItem('projectNoticeForm')) {
  //   form.value = JSON.parse(window.sessionStorage.getItem('projectNoticeForm')!)
  //   times.value = [form.value.declareStartTime, form.value.declareEndTime]
  //   if (window.sessionStorage.getItem('projectNoticeFormFileList')) {
  //     fileList.value = JSON.parse(window.sessionStorage.getItem('projectNoticeFormFileList')!)
  //   }
  // }

  if (route.query.id) {
    getProjectNoticesDetails({ id: route.query.id as string })
  }

  getDicList({ })
})
</script>

<style lang="scss" scoped>
.publish-notices {
  --at-apply: flex flex-col h-full bg-white;

  .title {
    --at-apply: text-20px font-bold border-b border-#E5E6EB py-16px pl-20px border-b-solid;
  }

  &-content {
    --at-apply: p-30px flex-1 overflow-y-auto;
  }

  &-btns {
    --at-apply: flex py-16px items-center justify-center pt-20px pb-20px;
    border-top: 1px solid #E5E6EB;
  }
}

:deep(.editor) {
  width: 100%;
}
</style>